<template>
  <div class="wrap">
    <div class="code_form">
      <div class="code_title">输入验证码</div>
      <div class="code_tips">验证码已发送至+86 {{ form.username }}</div>
      <div class="code_box">
        <VCode @code="form.password = $event" />
      </div>
      <div
        :style="{color: codeTime === 60 ? '#ff8002' : 'rgba(0, 0, 0, 0.45)'}"
        class="code_get"
        @tap="getVCdoe"
      >
        {{ getVCodeBtn }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import VCode from '@C/VCodeKeyBoard.vue'
import { Msg } from '@C/Msg'
import { newSendSms, oldSendSms } from '@P/Login/requset'
import { onLoad, storeState, storeCommit } from '@U/common'
import { partner_login_reg } from '@P/Login/Partner'

onLoad(() => {
  form.username = storeState.loginForm.username
  codeTimer.value = setInterval(() => {
    --codeTime.value
    if (codeTime.value < 1) {
      codeTime.value = 60
      clearInterval(codeTimer.value)
    }
  }, 1000)
})

// 验证码倒计时
const codeTime = ref(59)
const codeTimer = ref()
// 获取验证码
const getVCodeBtn = computed(() => `${codeTime.value !== 60 ? `${codeTime.value}s 后可重新获取` : '获取验证码'}`)
const getVCdoe = async () => {
  if (codeTime.value === 60) {
    codeTimer.value = setInterval(() => {
      --codeTime.value
      if (codeTime.value < 1) {
        codeTime.value = 60
        clearInterval(codeTimer.value)
      }
    }, 1000)
    let res = {}
    // 判断是否是新账号
    if (storeState.isNewAccount) res = await newSendSms(form.username).finally(() => {})
    else res = await oldSendSms(form.username).finally(() => {})
    if (res.code === 200) {
      Msg({ icon: 'success', msg: '已发送' })
    } else {
      clearInterval(codeTimer.value)
      codeTime.value = 60
      Msg({ icon: 'error', msg: res.msg })
    }
  }
}

// 表单
const form = reactive({
  username: '',
  password: '',
})

const num = ref(0)
watch(
    () => form.password,
    () => {
      if (form.password.length === 6) {
        num.value += 1
        if (num.value === 1) {
          const oldForm = JSON.parse(JSON.stringify(storeState.loginForm))
          storeCommit('loginForm', { ...oldForm, password: form.password })
          num.value = 0
          return partner_login_reg()
        }
      }
    },
)
</script>

<style lang="less" scoped>
.wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 242rpx 66rpx 60rpx;
  background: white;
  .code_form {
    flex: 1 1;
    width: 100%;
    .code_title {
      width: 100%;
      height: 66rpx;
      font-size: 48rpx;
      opacity: 0.85;
      margin-bottom: 2rpx;
    }
    .code_tips {
      width: 100%;
      height: 34rpx;
      margin-bottom: 52rpx;
      font-size: 24rpx;
      opacity: 0.45;
    }
    .code_box {
      height: 85rpx;
      margin-bottom: 46rpx;
    }
  }
  .code_get {
    height: 34rpx;
    color: rgba(0, 0, 0, 0.45);
    font-size: 24rpx;
  }
}
</style>
